# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/7/20'
# __name__ = 'imagesync_helper.py'

import os
import json
import re
import subprocess
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Create your code here.

class ImageSyncHelper():
    def __init__(self, registry, username, password):
        self.registry = registry
        self.username = username
        self.password = password
        self.toolspath = os.path.join(BASE_DIR, 'tools')
        self.tool = os.path.join(self.toolspath, 'image-syncer')

        

    def _dump_config(self, images={}, t='demo'):
        cpath = os.path.join(self.toolspath, '.tmp')
        if not os.path.exists(cpath):
            os.mkdir(cpath)
        cfile = os.path.join(cpath, "config.{}.json".format(t))
        data = {"auth":
                    {self.registry: {"username": self.username, "password": self.password}},
                "images": images}

        with open(cfile, 'w') as fr:
            fr.write(json.dumps(data, indent=4))
        return cfile

    def sync(self, images={},  t='demo', proc=5):
        config = self._dump_config(images, t)
        cmd = [self.tool, '--config', config, '--proc', str(proc)]
        pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
        output, error = pipe.communicate()
        g = re.search("Finished, ([\d]+) sync tasks failed, ([\d]+) tasks generate failed", str(output), re.DOTALL)
        if g:
            sync_task_fail_count = int(g.group(1)) + int(g.group(2))
            if sync_task_fail_count == 0:
                return True
            else:
                return False
        else:
            return False



if __name__=='__main__':
    import sys
    registry = 'registry.cn-hangzhou.aliyuncs.com'
    username = sys.argv[1]
    password = sys.argv[2]
    src = 'registry.cn-hangzhou.aliyuncs.com/522875917/etcd:2.0.12'
    dest = 'registry.cn-hangzhou.aliyuncs.com/test981/etcd'
    ihelper = ImageSyncHelper(registry, username, password)
    ret=ihelper.sync({src: dest})
    print(ret)
